package com.alliky.core.net.interceptor;

import com.alibaba.fastjson.JSON;
import com.alliky.core.util.KLog;
import com.alliky.core.util.StringUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.HashMap;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class LogInterceptor implements Interceptor {

    private static final String TAG = "X_HTTP";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Charset UTF8 = Charset.forName("UTF-8");
        //打印请求报文
        Request request = chain.request();
        //打印请求头
        RequestBody requestBody = request.body();
        String reqBody = null;
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            reqBody = buffer.readString(charset);
        }

        // 打印返回报文
        // 先执行请求，才能够获取报文
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        String respBody = null;
        if (responseBody != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    e.printStackTrace();
                }
            }
            respBody = buffer.clone().readString(charset);
        }

        HashMap headers = new HashMap();

        for (int i = 0; i < request.headers().size(); i++) {
            headers.put(request.headers().name(i), request.headers().value(i));
        }

        HashMap params = new HashMap();
        if (StringUtils.isNotBlank(reqBody)) {
            String[] arr = reqBody.split("&");
            for (int i = 0; i < arr.length; i++) {
                String[] arr0 = arr[i].split("=");
                params.put(arr0[0], arr0[1]);
            }
        }

        KLog.d(TAG, String.format("\n%s\nURL: %s\nHeaders: %s\nParams: %s\nResponse: %s\n%s",
                lineStart, response.request().url(), JSON.toJSONString(headers), JSON.toJSONString(params), respBody, lineEnd));
        return response;
    }

    String lineStart = "╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════";
    String lineEnd = "╚══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════";
}
